﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;


namespace advadev.CanOpen
{

    /// <summary>
    /// Represents a network management command write transfer
    /// </summary>
    public class NetworkManagementCommandWriteTransfer : ITransfer
    {

        /// <summary>for internal use</summary>
        private bool _isMasterTransfer;
        /// <summary>for internal use</summary>
        private bool _isTransferCompleteAfterSending;
        /// <summary>for internal use</summary>
        private CanOpenMessage _receivedCanOpenMessage;
        /// <summary>for internal use</summary>
        private NetworkManagementCommandReceivedEventHandler _networkManagementCommandReceivedEventHandler;
        /// <summary>for internal use</summary>
        private Collection<CanOpenMessage> _pendingSendMessages = new Collection<CanOpenMessage>();
        /// <summary>for internal use</summary>
        private ReadOnlyCollection<CanOpenMessage> _pendingSendMessagesReference;
        /// <summary>
        /// Default master COB-ID
        /// </summary>
        static public readonly UInt16 DefaultMasterCobId = 0x00;


        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementCommandWriteTransfer class by the given parameter
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="networkManagementCommandReceivedEventHandler">
        /// Network management command received event handler (or null)
        /// </param>
        private NetworkManagementCommandWriteTransfer(CanOpenMessage receivedCanOpenMessage, NetworkManagementCommandReceivedEventHandler networkManagementCommandReceivedEventHandler)
        {
            _isMasterTransfer = false;
            _receivedCanOpenMessage = receivedCanOpenMessage;
            _networkManagementCommandReceivedEventHandler = networkManagementCommandReceivedEventHandler;
        }

        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementCommandWriteTransfer class by the given parameter
        /// </summary>
        /// <param name="networkManagementCommandSpecifier">
        /// Network management command specifier to send with the network
        /// management command
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device to write the network management command to
        /// (must be in the range of 1..127)
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public NetworkManagementCommandWriteTransfer(NetworkManagementCommandSpecifier networkManagementCommandSpecifier, byte nodeId)
            : this(networkManagementCommandSpecifier, nodeId, DefaultMasterCobId)
        {
        }

        /// <summary>
        /// Initializes a new instance of the
        /// NetworkManagementCommandWriteTransfer class by the given parameter
        /// </summary>
        /// <param name="networkManagementCommandSpecifier">
        /// Network management command specifier to send with the network
        /// management command
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device to write the network management command to
        /// (must be in the range of 1..127)
        /// </param>
        /// <param name="masterCobId">
        /// Master COB-ID
        /// </param>
        /// <exception cref="ArgumentOutOfRangeException">
        /// Will be thrown if the node id is not in the range of 1..127
        /// </exception>
        public NetworkManagementCommandWriteTransfer(NetworkManagementCommandSpecifier networkManagementCommandSpecifier, byte nodeId, UInt16 masterCobId)
        {
            // check parameter
            if (!(1 <= nodeId && nodeId <= 127))
            {
                throw new ArgumentOutOfRangeException("nodeId", "The node id must be in the range of 1..127");
            }

            // initializaton
            _isMasterTransfer = true;
            NodeId = nodeId;
            MasterCobId = masterCobId;
            NetworkManagementCommandSpecifier = networkManagementCommandSpecifier;
        }


        /// <summary>
        /// Gets or sets the node id
        /// </summary>
        private byte NodeId
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the network management command specifier
        /// </summary>
        private NetworkManagementCommandSpecifier NetworkManagementCommandSpecifier
        {
            get;
            set;
        }

        /// <summary>
        /// Gets or sets the master COB-ID
        /// </summary>
        private UInt16 MasterCobId
        {
            get;
            set;
        }


        /// <summary>
        /// Checks if the given received can open message is a network
        /// management command write transfer request and if so it returns as
        /// out parameter a matching network management command write transfer
        /// instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device that received the given can open message
        /// </param>
        /// <param name="networkManagementCommandWriteTransfer">
        /// A matching network management command write transfer instance
        /// </param>
        /// <param name="networkManagementCommandReceivedEventHandler">
        /// Network management command received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a network management
        /// command write transfer request, false otherwise
        /// </returns>
        static public bool IsNetworkManagementCommandWriteTransfer(CanOpenMessage receivedCanOpenMessage, byte nodeId, out NetworkManagementCommandWriteTransfer networkManagementCommandWriteTransfer, NetworkManagementCommandReceivedEventHandler networkManagementCommandReceivedEventHandler)
        {
            return IsNetworkManagementCommandWriteTransfer(receivedCanOpenMessage, nodeId, out networkManagementCommandWriteTransfer, DefaultMasterCobId, networkManagementCommandReceivedEventHandler);
        }

        /// <summary>
        /// Checks if the given received can open message is a network
        /// management command write transfer request and if so it returns as
        /// out parameter a matching network management command write transfer
        /// instance
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <param name="nodeId">
        /// Node id of the device that received the given can open message
        /// </param>
        /// <param name="networkManagementCommandWriteTransfer">
        /// A matching network management command write transfer instance
        /// </param>
        /// <param name="masterCobId">
        /// Master COB-ID
        /// </param>
        /// <param name="networkManagementCommandReceivedEventHandler">
        /// Network management command received event handler (or null)
        /// </param>
        /// <returns>
        /// True if the received can open message is a network management
        /// command write transfer request, false otherwise
        /// </returns>
        static public bool IsNetworkManagementCommandWriteTransfer(CanOpenMessage receivedCanOpenMessage, byte nodeId, out NetworkManagementCommandWriteTransfer networkManagementCommandWriteTransfer, UInt16 masterCobId, NetworkManagementCommandReceivedEventHandler networkManagementCommandReceivedEventHandler)
        {
            // check parameter
            if (receivedCanOpenMessage == null)
            {
                networkManagementCommandWriteTransfer = null;
                return false;
            }

            // check node id
            if (receivedCanOpenMessage.Byte1 != nodeId || !(1 <= nodeId && nodeId <= 127))
            {
                networkManagementCommandWriteTransfer = null;
                return false;
            }

            // check COB-ID
            if (receivedCanOpenMessage.CanId != masterCobId)
            {
                networkManagementCommandWriteTransfer = null;
                return false;
            }

            // create transfer instance
            networkManagementCommandWriteTransfer = new NetworkManagementCommandWriteTransfer(receivedCanOpenMessage, networkManagementCommandReceivedEventHandler);
            return true;
        }

        /// <summary>
        /// Starts the master transfer
        /// </summary>
        private void startMasterTransfer()
        {
            UInt16 canId = MasterCobId;
            byte byte0 = (byte)NetworkManagementCommandSpecifier;
            byte byte1 = NodeId;
            _pendingSendMessages.Add(new CanOpenMessage(canId, byte0, byte1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 2));
            _isTransferCompleteAfterSending = true;
        }

        /// <summary>
        /// Starts the slave transfer
        /// </summary>
        private void startSlaveTransfer()
        {
            // process data
            if (_networkManagementCommandReceivedEventHandler != null)
            {
                NetworkManagementCommandSpecifier networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.Unkown;
                if (_receivedCanOpenMessage.Byte0 == (byte)NetworkManagementCommandSpecifier.StartRemoteNode)
                {
                    networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.StartRemoteNode;
                }
                else if (_receivedCanOpenMessage.Byte0 == (byte)NetworkManagementCommandSpecifier.StopRemoteNode)
                {
                    networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.StopRemoteNode;
                }
                else if (_receivedCanOpenMessage.Byte0 == (byte)NetworkManagementCommandSpecifier.EnterPreOperational)
                {
                    networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.EnterPreOperational;
                }
                else if (_receivedCanOpenMessage.Byte0 == (byte)NetworkManagementCommandSpecifier.ResetNode)
                {
                    networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.ResetNode;
                }
                else if (_receivedCanOpenMessage.Byte0 == (byte)NetworkManagementCommandSpecifier.ResetCommunication)
                {
                    networkManagementCommandSpecifier = NetworkManagementCommandSpecifier.ResetCommunication;
                }
                _networkManagementCommandReceivedEventHandler(this, new NetworkManagementCommandReceivedEventArgs(networkManagementCommandSpecifier));
            }

            // end transfer
            TransferComplete = true;
        }


        #region ITransfer implementation
        /// <summary>
        /// Gets a flag indicating whether the transfer is complete (after
        /// sending the pending send messages)
        /// </summary>
        public bool TransferComplete
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the abort code (null for successful transfers)
        /// </summary>
        public CanOpenAbortCode AbortCode
        {
            get;
            private set;
        }

        /// <summary>
        /// Gets the pending send messages
        /// </summary>
        public ReadOnlyCollection<CanOpenMessage> PendingSendMessages
        {
            get
            {
                if (_pendingSendMessagesReference == null)
                {
                    _pendingSendMessagesReference = new ReadOnlyCollection<CanOpenMessage>(_pendingSendMessages);
                }
                return _pendingSendMessagesReference;
            }
        }


        /// <summary>
        /// Starts the transfer
        /// </summary>
        public void Start()
        {
            if (_isMasterTransfer)
            {
                startMasterTransfer();
            }
            else
            {
                startSlaveTransfer();
            }
        }

        /// <summary>
        /// Times out the transfer
        /// </summary>
        public void TimeOut()
        {
            AbortCode = new CanOpenAbortCode(0x00, 0x00, 0x04, 0x05);
        }

        /// <summary>
        /// Finalizes the transfer
        /// </summary>
        public void FinalizeTransfer()
        {
        }

        /// <summary>
        /// Continues the transfer after sending messages
        /// </summary>
        public void ContinueAfterSendingMessages()
        {
            _pendingSendMessages.Clear();
            if (_isTransferCompleteAfterSending)
            {
                TransferComplete = true;
            }
        }

        /// <summary>
        /// Processes the received message
        /// </summary>
        /// <param name="receivedCanOpenMessage">
        /// Received can open message
        /// </param>
        /// <returns>
        /// True, if the given can open message was related to this transfer,
        /// false otherwise
        /// </returns>
        public bool ProcessReceivedMessage(CanOpenMessage receivedCanOpenMessage)
        {
            return false;
        }
        #endregion ITransfer implementation

    }

}
